<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>用户管理</span>
      </div>
    </template>

    <div class="search-form">
      <div class="toobar-button">
        <el-button type="primary" @click="addUser" v-if="getBtnPermission('btn:addUser')">
          <template #icon>
            <img src="../../assets/images/add_member.png" alt="">
          </template>
          新增用户
        </el-button>
		    <el-button type="primary" @click="addOrgUser" v-if="getBtnPermission('btn:addOrgUser')">
          <template #icon>
            <img src="../../assets/images/add_member.png" alt="">
          </template>
          新增组织用户
        </el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent="() => onSubmit">
        <el-form-item>
          <el-input placeholder="请输入用户姓名" v-model="formInline.para" @keyup.enter="onSubmit">
            <template #suffix>
              <el-icon class="el-input__icon curP"  @click="onSubmit"><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      
    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="userData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
      >
        <el-table-column
          v-for="(tableItem, tableIndex) in userTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="160"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              v-if="row.status == 1 && getBtnPermission('btn:changeUserStatus')"
              @click="userChange(row)"
              :disabled="buttonDisabled"
            >禁用</el-button>
            <el-button
              type="warning"
              link
              v-if="row.status == 0 && getBtnPermission('btn:changeUserStatus')"
              @click="userChange(row)"
              :disabled="buttonDisabled"
            >恢复</el-button>
            <el-button
              link
              @click="userDelete(row)"
              style="color: #5897DB;"
              :disabled="buttonDisabled"
              v-if="getBtnPermission('btn:deleteUser')"
            >删除</el-button>
            <el-button
              link
              @click="userDetail(row)"
              style="color: #5897DB;"
              :disabled="buttonDisabled"
            >查看详情</el-button>
            <el-button
              link
              @click="userEdit(row)"
              style="color: #5897DB;"
              :disabled="buttonDisabled"
              v-if="getBtnPermission('btn:editUser')"
            >编辑</el-button>
			      <el-button
              link
              @click="orgUserEdit(row)"
              style="color: #5897DB;"
              :disabled="buttonDisabled"
              v-if="getBtnPermission('btn:editOrgUser')"
            >编辑组织用户</el-button>
            <el-button
              link
              @click="passwordEdit(row)"
              style="color: #5897DB;"
              :disabled="buttonDisabled"
              v-if="getBtnPermission('btn:editUserPassword')"
            >修改密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :page-count="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <el-dialog title="修改密码" v-model="dialogVisible" draggable @close="cancelPassword">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
        :rules="rules"
      >
        <el-form-item label="原密码" prop="Password">
          <el-input v-model="ruleForm.Password" placeholder="请输入原密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="NewPassword">
          <el-input v-model="ruleForm.NewPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="NewPassword2">
          <el-input v-model="ruleForm.NewPassword2" placeholder="请再次确认新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-button">
        <el-button @click="cancelPassword" :loading="passwordButtonLoading">取消</el-button>
        <el-button type="primary" @click="submitPassword" :loading="passwordButtonLoading">修改</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script setup name="application">
import { useRouter } from 'vue-router';
import { computed, onMounted, ref } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/http/index';
import { format } from '@/plugins/moment.js'
import { useAuthStore } from '@/stores/modules/auth.js';

/* 路由 */
const router = useRouter()

const authStore = useAuthStore()

/* 所有按钮权限 */
const btnPermissionList = ref([])
btnPermissionList.value = authStore.base_auth_tree.find(item => item.controlName == 'btn_permission')?.children

/* 查询是否有权限 */
const getBtnPermission = (name) => {
  let flag = false
  if( btnPermissionList.value.find(item => item.controlName == name && item.selected == 1) ) {
    flag = true
  }
  return flag
}

onMounted(() => {
  onSubmit()
})

/* 搜索表单 */
const formInline = ref({
  para: "",
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(15)
const currentPage = ref(1)

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const userData = ref([])

/* 状态字段过滤 */
const statusFormatter = (row, column, cellValue) => {
  return cellValue == "1" ? "正常" : "停用"
}

/* 创建时间字段过滤 */
const getCreateTime = (cellValue) => {
  return format(cellValue)
}

/* 表格字段 */
const userTableColumns = ref([
  { field: "name", label: "姓名", minWidth: "120" },
  { field: "loginName", label: "账号", minWidth: "120" },
  { field: "email", label: "邮箱", minWidth: "120" },
  { field: "createTime", label: "注册日期", minWidth: "120", formatter:(row, column, cellValue)=>{ return getCreateTime(cellValue)} },
  { field: "status", label: "状态", minWidth: "120", formatter: statusFormatter },
])

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pagenum: currentPage.value,
    pagesize: pageSize.value,
    para: formInline.value.para,
    userId: authStore.base_auth_userinfo?.id
  }
  http.$GET("/UserManager/GetUserList", params).then(res => {
    loading.value = false
    if (res.isError) return ElMessage.warning(res.message)
    userData.value = res.result.content
    dataTotal.value = res.result.total_num
  }).catch(() => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 点击新建 */
const addUser = () => {
  router.push({
    path: "/UserManager/UserEdit",
    query: { type: 'add' }
  })
}

/* 点击编辑 */
const userEdit = (row) => {
  router.push({
    path: "/UserManager/UserEdit",
    query: { type: 'edit', id: row.id }
  })
}

/* 点击新建组织用户 */
const addOrgUser = () => {
  router.push({
    path: "/UserManager/orgUserEdit",
    query: { type: 'add' }
  })
}

/* 点击编辑组织用户 */
const orgUserEdit = (row) => {
  router.push({
    path: "/UserManager/orgUserEdit",
    query: { type: 'edit', id: row.id }
  })
}

/* 操作列按钮禁用 */
const buttonDisabled = ref(false)

/* 点击更改状态 */
const userChange = (row) => {
  ElMessageBox.confirm(
    `确定更改此条数据的状态吗？`,
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    buttonDisabled.value = true
    let params = {
      id: row.id,
      status: ""
    }

    if(row.status == 0) {
      params.status = 1
    } else {
      params.status = 0
    }

    const formData = new FormData()
    for(let k in params) {
      formData.append(k ,params[k])
    }
    http.$POST("/UserManager/UpdateUser", formData).then(res => {
      buttonDisabled.value = false
      if(res.isError) return ElMessage.warning("操作失败")
      onSubmit()
    }).catch(() => {
      buttonDisabled.value = false
      ElMessage.warning("操作失败")
    })
  }).catch(() => {
    ElMessage.info("已取消更改状态操作")
  })
}

/* 点击删除 */
const userDelete = (row) => {
  ElMessageBox.confirm(
    `确定删除此条数据吗？`,
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    buttonDisabled.value = true
    let params = {
      id: row.id,
    }

    const formData = new FormData()
    for(let k in params) {
      formData.append(k ,params[k])
    }
    http.$POST("/UserManager/DelUser", formData).then(res => {
      buttonDisabled.value = false
      if(res.isError) return ElMessage.warning("操作失败")
      onSubmit()
    }).catch(() => {
      buttonDisabled.value = false
      ElMessage.warning("操作失败")
    })
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}

/* 点击查看详情 */
const userDetail = (row) => {
  let { href } = router.resolve({
    path: "/UserManager/UserDetail",
    query: { id: row.id }
  })
  window.open(href, "_blank")
}

/* 点击修改密码 */
const passwordEdit = (row) => {
  ruleForm.value.Id = row.id
  dialogVisible.value = true
}

/* 修改密码弹窗 */
const dialogVisible = ref(false)
const ruleFormRef = ref(null)
const ruleForm = ref({
  Id: "",
  Password: "",
  NewPassword: "",
  NewPassword2: "",
})
/* 确认密码校验 */
const checkNewPassword2 = (rule, value, callback) => {
	if(value !== ruleForm.value.NewPassword){
		callback(new Error('与第一次输入的新密码不一致'))
	} else {
    callback()
  }
}
const rules = ref({
  Password: [
    { required: true, message: '请输入原密码', trigger: 'change' }
  ],
  NewPassword: [
    { required: true, message: '请输入新密码', trigger: 'change' }
  ],
  NewPassword2: [
    { required: true, message: '请再次确认新密码', trigger: 'change' },
    { validator: checkNewPassword2, message: '与第一次输入的新密码不一致', trigger: 'blur' }
  ],
})

/* 取消修改 */
const cancelPassword = () => {
  dialogVisible.value = false
  ruleFormRef.value.resetFields()
}

const passwordButtonLoading = ref(false)

/* 提交修改 */
const submitPassword = () => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      let params = JSON.parse(JSON.stringify(ruleForm.value))
      const formData = new FormData()
      for(let k in params) {
        formData.append(k ,params[k])
      }
      http.$POST("/UserManager/ChangePwd", formData).then((res) => {
        if(res.isError) return ElMessage.warning(res.message)
        ElMessage.success("操作成功")
        cancelPassword()
      })
    }else{
      ElMessage.warning("请先完成必填项")
    }
  })
}

</script>
<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>